package com.stone.starter.core.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * 缓存变更异常
 *
 * @author Mr_wenpan@163.com 2021/08/06 10:38
 */
public class CacheModifyException extends RuntimeException {

    private static final Logger logger = LoggerFactory.getLogger(CacheModifyException.class);

    private final transient Object[] parameters;

    private final String message;

    public CacheModifyException(String message, Throwable cause, Object[] parameters) {
        super(String.format(message, parameters), cause);
        this.parameters = parameters;
        this.message = message;
    }

    public CacheModifyException(String message, Object... parameters) {
        super(String.format(message, parameters));
        this.parameters = parameters;
        this.message = message;
    }

    public Object[] getParameters() {
        return parameters;
    }

    public String getCode() {
        return message;
    }

    /**
     * 获取异常堆栈信息
     *
     * @return java.lang.String
     * @author Mr_wenpan@163.com 2021/8/6 10:45 上午
     */
    public String getTrace() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps;
        try {
            ps = new PrintStream(baos, false, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            logger.error("Error get trace, unsupported encoding.", e);
            return null;
        }
        printStackTrace(ps);
        ps.flush();
        return new String(baos.toByteArray(), StandardCharsets.UTF_8);
    }

}
